package com.suep.lesson_manage.controller;

import com.suep.lesson_manage.application.dto.AddLessonRequestDto;
import com.suep.lesson_manage.application.dto.LessonDto;
import com.suep.lesson_manage.application.dto.UpdateLessonRequestDto;
import com.suep.lesson_manage.application.service.LessonService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@AllArgsConstructor
@RestController
@RequestMapping("api/lesson")
public class LessonController {

    private final LessonService lessonService;

    /**
     * Query by PathVariable or RequestParam
     *
     * @param section_id section id
     * @return lesson
     */
    //swagger annotation
    @Operation(
            summary = "根据课节号查询课节信息",
            description = "根据课节号查询具体课节信息",
            parameters = {
                    @Parameter(name = "section_id", description = "课节编号", required = true, examples = {
                            @ExampleObject(value = "1", description = "课节号为1的课节信息"),
                    })
            },
            responses = {
                    @ApiResponse(responseCode = "200", description = "成功获取课节信息",content = @Content(schema = @Schema(implementation = LessonDto.class))),
                    @ApiResponse(responseCode = "404",description = "课节信息不存在",content = @Content)
            }
    )
    //spring annotation
    //以section_id获取单个课节信息
    @GetMapping("/get/{section_id}")
    public ResponseEntity<LessonDto> findLessonById(@PathVariable(name = "section_id") Integer section_id) {
        var lesson = lessonService.getLessonById(section_id);
        if (lesson == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(lesson);
    }
    //获取所有课节信息
    @GetMapping("/get/all")
    public List<LessonDto> findAllLessons() {
        return this.lessonService.getAllLessons();
    }

    // 获取课节表行数的接口
    @Operation(
            summary = "获取课节表的行数",
            description = "查询课节表中总共有多少条记录"
    )
    @GetMapping("/count")
    public ResponseEntity<Long> getLessonSectionCount() {
        long count = lessonService.getLessonSectionCount();
        return ResponseEntity.ok(count);
    }

    //插入新课节信息
    @Operation(summary = "新增课节信息", description = "新增一个课节信息")
    @PostMapping("/add")
    public ResponseEntity<?> addLesson(
            @RequestBody AddLessonRequestDto addLessonRequestDto,
            BindingResult bindingResult){
        //request validation
        if(bindingResult.hasErrors()){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(this.buildValidationError(bindingResult));
        }

        var result =this.lessonService.addLesson(addLessonRequestDto);
        if(result.equals("success")){
            return ResponseEntity.ok().build();
        }else{
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    private List<String> buildValidationError(BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return bindingResult.getFieldErrors().stream()
                    .map(error -> error.getField() + ": " + error.getDefaultMessage()).  collect(Collectors.toList());
        }
        return null;
    }
    //删除指定课节
    @Operation(summary = "删除课节信息", description = "删除一个课节信息")
    @DeleteMapping(path="/delete/{section_id}")
    public void removeLesson(@PathVariable(name = "section_id") Integer section_id) {
        this.lessonService.removeLesson(section_id);
    }
    //更新指定课节信息
    @Operation(summary = "更新课节信息", description = "更新一个课节信息")
    @PostMapping(path="/update/{section_id}")
    public ResponseEntity<?> updateLesson(
            @PathVariable(name = "section_id") Integer section_id,
            @RequestBody UpdateLessonRequestDto updateLessonRequestDto,
            BindingResult bindingResult){
        //request validation
        if(bindingResult.hasErrors()){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(this.buildValidationError(bindingResult));
        }
        var result =this.lessonService.updateLesson(section_id,updateLessonRequestDto);
        if(result.equals("success")){
            return ResponseEntity.ok().build();
        }else{
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

}
